import "./utils/msg"
import { $http } from '@escook/request-miniprogram'
wx.$http = $http
$http.baseUrl = 'https://live-api.itheima.net'

App({
  /**
   * 当小程序初始化完成时，会触发 onLaunch（全局只触发一次）
   */
  onLaunch: function () {
  },
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    this.getUserInfo()
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
  },
  async getUserInfo() {
    if (wx.getStorageSync('token')) {
      const result = await wx.$http.get('/userInfo')
      this.globalData.userInfo = result.data.data
    }
  },
  onRouteChange: function (path, query) {
    console.log("路由跳转到：" + path);
    console.log(query)
    // 验证用户是否登录，未登录则跳转到登录页面
    if (!wx.getStorageSync('token') && path !== '/pages/login/login') {
      this.globalData.url = path
      this.globalData.urlData = query
      wx.redirectTo({
        url: '/pages/login/login'
      })
      return false
    }
    return true
  },
  globalData: {
    userInfo: {},
    url: '',
    urlData: {}
  },
  /**
   * 当小程序启动，或从后台进入前台显示，会触发 onShow
   */
  onShow: function (options) {
  },
  /**
   * 当小程序从前台进入后台，会触发 onHide
   */
  onHide: function () {
  },
  /**
   * 当小程序发生脚本错误，或者 api 调用失败时，会触发 onError 并带上错误信息
   */
  onError: function (msg) {
  }
})

